<template>

	<button @click="handleSubmit">提交</button>

</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';


	//交互
	import * as anchor from "@coral-xyz/anchor";
	import {
		AnchorError
	} from '@coral-xyz/anchor';

	//import { Nftmint } from "../types/nftmint";
	import {
		Keypair,
		PublicKey,
		SYSVAR_RENT_PUBKEY,
		SystemProgram,
		LAMPORTS_PER_SOL
	} from "@solana/web3.js";
	import {
		Connection,
		clusterApiUrl,
		Transaction
	} from '@solana/web3.js';

	import {
		ASSOCIATED_PROGRAM_ID,
		TOKEN_PROGRAM_ID,
		associatedAddress
	} from "@coral-xyz/anchor/dist/cjs/utils/token";
	import {
		BN
	} from "bn.js";


	import {
		NATIVE_MINT,
	} from '@solana/spl-token';

	import {
		notify
	} from "@kyvg/vue3-notification";
	import {
		useWallet
	} from 'solana-wallets-vue'

	import store from '../vuex';
	import {
		useRoute
	} from 'vue-router';
	import {useWorkspace} from "../vuex/store";
	import bigInt from 'big-integer';
	const route = useRoute();
	const METADATA_PROGRAM = new PublicKey("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
	
	const pinData_string = route.query.pinData;
	const pinData = JSON.parse(pinData_string);
	console.log(pinData);


	const feeRecipient = pinData.feeRecipient;
	const nftName = pinData.nftName;const symbol = pinData.nftSymbol;
	const uri = pinData.uri;
	const collectionPDA = new PublicKey(pinData.collectionMint);
	
	let price = pinData.price;

	async function mintNftBuilder(){
		const workspaceValue = store.state.workspace.value;
		if (!workspaceValue) {
			console.error('Workspace is not initialized.');
			return;
		}

		const {
			wallet,
			connection,
			provider,
			program
		} = workspaceValue;
		const {
			publicKey,
			connected,
			sendTransaction
		} = useWallet();
		let timestamp = Math.floor(new Date().getTime() / 1000);
		const ticket = anchor.web3.PublicKey.findProgramAddressSync([new BN(timestamp).toArrayLike(Buffer, "le", 8)], program.programId)[0];
		const isPreSale = true;
		const mint = anchor.web3.Keypair.generate();
		// notify({
		// 	title: `mint ${mint.publicKey.toBase58()}`
		// });
		console.log("ticket", ticket.toBase58());
		let metadataPDA = anchor.web3.PublicKey.findProgramAddressSync(
			[Buffer.from("metadata"), METADATA_PROGRAM.toBytes(), mint.publicKey.toBytes()],
			METADATA_PROGRAM
		)[0];

		let masterEditionPDA = anchor.web3.PublicKey.findProgramAddressSync(
			[Buffer.from("metadata"), METADATA_PROGRAM.toBytes(), mint.publicKey.toBytes(), Buffer.from(
				"edition")],
			METADATA_PROGRAM
		)[0];

		const tokenAccount = await associatedAddress({
			mint: mint.publicKey,
			owner: provider.wallet.publicKey
		});

	
		let collectionMetadataPDA = anchor.web3.PublicKey.findProgramAddressSync(
			[Buffer.from("metadata"), METADATA_PROGRAM.toBytes(), collectionPDA.toBytes()],
			METADATA_PROGRAM
		)[0];

		let collectionMasterEditionPDA = anchor.web3.PublicKey.findProgramAddressSync(
			[Buffer.from("metadata"), METADATA_PROGRAM.toBytes(), collectionPDA.toBytes(), Buffer.from("edition")],METADATA_PROGRAM
		)[0];

		const modifyComputeUnits =
			anchor.web3.ComputeBudgetProgram.setComputeUnitLimit({
				units: 500_000
			});

		let perfIns = [];
		perfIns.push(modifyComputeUnits);

		let user = provider.wallet.publicKey;
		const userInfo = anchor.web3.PublicKey.findProgramAddressSync([user.toBytes(), collectionPDA.toBytes()],
			program.programId)[0]; //usdc-feevault

		const cardInfo = anchor.web3.PublicKey.findProgramAddressSync([Buffer.from("card"), collectionPDA
				.toBytes()
			],
			program.programId)[0]; //nft setting
		console.log("cardInfo", cardInfo.toBase58());


		const solLamports = await connection.getBalance(publicKey.value, 'confirmed');

		const balance = solLamports / LAMPORTS_PER_SOL;
		console.log(price,solLamports,balance);
		console.log("feeRecipient:",feeRecipient);
		

		if (solLamports < price) {
		
			console.log('error', '余额不足');
		} else{

		try {
		
			const tx = await program.methods
				.createItem(
					{
						name: nftName,      
						symbol: symbol, 
						uri: uri,  //uri
						timestamp: new BN(timestamp),
						isPreSale: isPreSale, 
					}	
				
				)
				.accounts({
					user: user,
					cardInfo: cardInfo,
					collectionMint: collectionPDA,
					collectionMetadataAccount: collectionMetadataPDA,
					collectionMasterEdition: collectionMasterEditionPDA,
					nftMint: mint.publicKey,
					metadataAccount: metadataPDA,
					masterEdition: masterEditionPDA,
					tokenAccount: tokenAccount,
					feeRecipient:feeRecipient,
					ticket:ticket,
					systemProgram: SystemProgram.programId,
					tokenProgram: TOKEN_PROGRAM_ID,
					associatedTokenProgram: ASSOCIATED_PROGRAM_ID,
					tokenMetadataProgram: METADATA_PROGRAM,
					rent: SYSVAR_RENT_PUBKEY,

				})
				.preInstructions([modifyComputeUnits])
				.signers([mint])
				.rpc();

			console.log("Your transaction signature", tx);

		} catch (error) {

			if (error instanceof AnchorError) {


				const code = error.error.errorCode.code;
				const number = error.error.errorCode.number;
				const message = error.error.errorMessage;

				console.error('捕获到的错误: ', code, number, message);
				// 在这里处理错误，例如显示错误消息给用户
			} else {
				// 处理其他类型的错误
				console.error('未知错误: ', error);
			}
		}



		}
	
			
			
		
	}
	const handleSubmit = async (event) => {
		// 阻止表单的默认提交行为
		event.preventDefault();
	
		
		store.commit('initWorkspace', {
      callback: () => {
        mintNftBuilder();
      }
    });



	};
</script>

<style scoped>
	.form-page {
		color: #ffffff;
		/* 文字颜色为白色，以提高对比度 */
		background-color: #333333;
		/* 表单页面背景颜色 */
		padding: 20px;
		/* 添加内边距 */
		border-radius: 8px;
		/* 添加圆角 */
		width: 80%;
		/* 调整宽度为屏幕的80% */
		max-width: 700px;
		/* 最大宽度限制 */
		margin: 20px auto;
		/* 增加上下边距并水平居中 */
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		/* 添加阴影效果 */
	}

	.form-group {
		margin-bottom: 15px;
		/* 减少底部边距 */
	}

	label {
		display: block;
		margin-bottom: 5px;
		/* 减少标签下边距 */
		color: #bbbbbb;
		/* 标签文字颜色稍微淡一些，以区分输入框 */
		font-size: 0.9em;
		/* 减小字体大小 */
	}

	.data-display {
		padding: 10px;
		background-color: #444444;
		/* 数据显示背景颜色 */
		color: #dddddd;
		/* 数据显示文字颜色 */
		border-radius: 4px;
		/* 数据显示圆角 */
		margin-bottom: 10px;
		/* 数据显示下边距 */
		word-wrap: break-word;
		/* 防止内容溢出 */
	}

	input[type="number"],
	input[type="text"],
	input[type="datetime-local"] {
		width: 100%;
		/* 调整宽度为100% */
		padding: 10px;
		background-color: #444444;
		/* 输入框背景颜色 */
		color: #dddddd;
		/* 输入框文字颜色 */
		border: 1px solid #555555;
		/* 输入框边框颜色 */
		border-radius: 4px;
		/* 输入框圆角 */
		box-sizing: border-box;
		/* 确保宽度包括内边距和边框 */
	}

	button {
		padding: 10px 20px;
		background-color: #0056b3;
		/* 按钮背景颜色 */
		color: white;
		border: none;
		border-radius: 4px;
		/* 按钮圆角 */
		cursor: pointer;
		transition: background-color 0.3s;
		/* 添加过渡效果 */
		font-size: 0.9em;
		/* 减小字体大小 */
		margin-top: 15px;
		/* 减少按钮上边距 */
	}

	button:hover {
		background-color: #004080;
		/* 鼠标悬停时的按钮背景颜色 */
	}

	.pin-image {
		display: block;
		max-width: 100%;
		/* 确保图片不会超出容器宽度 */
		height: auto;
		/* 高度自动调整 */
		margin-top: 15px;
		/* 在图片上方添加间距 */
		border-radius: 4px;
		/* 图片圆角 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		/* 为图片添加阴影 */
	}
</style>
